<template>
  <AuModal
    v-model="showPopup"
    :title="title"
    :width="740"
    :padding="false"
    @handleConfirm="formRef.submit()"
    @close="close"
  >
    <div class="p-[14px]">
      <AuForm
        ref="formRef"
        :formData="formData"
        :formList="formList"
        :hiddenBtn="true"
        :hasUnfold="false"
        :label-width="150"
        @change="taskChange"
        @submit="handleFormSubmit"
      >
        <template #reminderSlot_behind>
          <el-checkbox-group
            v-if="remindSlotLabel === t('task_detail.form.week')"
            v-model="remindData.week"
            @change="changeRemind"
          >
            <el-checkbox
              v-for="item in WEEK_LIST(t)"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-checkbox-group>
          <el-checkbox-group
            v-else
            v-model="remindData.month"
            @change="changeRemind"
          >
            <el-checkbox
              v-for="item in 31"
              :key="item"
              :label="`${item}${t('task_detail.form.day')}`"
              :value="item"
            />
          </el-checkbox-group>
        </template>
      </AuForm>
    </div>
  </AuModal>
</template>

<script setup lang="ts">
import { AuModal } from "@/components/AuModal";
import { AuForm } from "@/components/AuForm";
import { computed, nextTick, ref, watch } from "vue";
// import { REMINDER_LIST } from "@/views/expiry/task/taskTime/constants";
import { WEEK_LIST, REMINDER_LIST } from "../constants";
import { cloneDeep } from "lodash-unified";
import {
  taskAdd,
  TaskAddModel,
  TaskListProp,
  TaskTypeListProp,
  taskUpd
} from "@/api/expiry/task";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  taskParam: {
    type: Object as PropType<{
      typeId: string;
      subId: string;
      versionId: string;
      taskId?: string;
    }>,
    default: () => ({})
  },
  typeList: {
    type: Array,
    default: () => []
  }
});
const emit = defineEmits(["update:modelValue", "confirm"]);
const showPopup = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const title = ref("");

const remindData = ref({
  week: [],
  month: []
});
const { t } = useI18n();
const formList = ref([
  {
    type: "input",
    key: "name",
    label: "task_detail.form.task_name",
    placeholder: "task_detail.form.enter_task_name",
    span: 12,
    required: true
  },
  {
    type: "input",
    key: "note",
    label: "task_detail.form.task_description",
    placeholder: "task_detail.form.enter_task_description",
    span: 12,
    required: true
  },
  {
    type: "select",
    key: "typeId",
    label: "task_detail.form.category",
    span: 12,
    placeholder: "task_detail.form.select_category",
    valueKey: "id",
    labelKey: "name",
    filterable: true,
    options: [],
    emptyValues: [null, undefined],
    defaultValue: ""
  },
  {
    type: "el-switch",
    key: "reminderType",
    label: "task_detail.form.single_reminder",
    span: 12,
    required: true,
    defaultValue: 2,
    activeValue: 1,
    inactiveValue: 2
  },
  {
    type: "select",
    key: "loopType",
    label: "task_detail.form.repeat_type",
    span: 12,
    placeholder: "task_detail.form.select_repeat_type",
    valueKey: "value",
    labelKey: "label",
    filterable: true,
    required: true,
    options: REMINDER_LIST(t)
  },
  {
    type: "date",
    key: "singleReminderTime",
    label: "task_detail.form.reminder_time",
    span: 12,
    placeholder: "task_detail.form.select_reminder_time",
    inType: "datetime",
    hidden: true,
    required: true,
    format: "YYYY-MM-DD HH:mm:ss",
    valueFormat: "YYYY-MM-DD HH:mm:ss"
  },
  {
    type: "el-time-picker",
    key: "reminderHour",
    label: "task_detail.form.reminder_time",
    span: 12,
    placeholder: "task_detail.form.select_reminder_time",
    required: true,
    format: "HH:mm:ss",
    valueFormat: "HH:mm:ss"
  },
  {
    type: "base",
    key: "reminderSlot",
    label: "",
    span: 24,
    slot: true,
    rules: [
      {
        validator: (rule: any, value: any, callback: any) => {
          const { valid, msg } = validateRemind();
          callback(valid ? undefined : msg);
        },
        trigger: "change"
      }
    ]
  }
]);
const remindSlotLabel = ref(t("task_detail.form.week"));
let curSubId = -1;
const formRef = ref(null);

const close = () => {
  emit("update:modelValue", false);
};

const typeChangeHandle = async (val: TaskTypeListProp["id"]) => {
  const find = props.typeList.find(
    (item: TaskTypeListProp) => item.id == val
  ) as TaskTypeListProp;
  curSubId = Number(find?.subId ?? -1);
  if (curSubId == 1 || curSubId == 2) {
    await taskChange({ key: "reminderType", value: 2 });
    formRef.value.setFormData({
      reminderType: 2
    });

    formRef.value.setFormProps(
      ["reminderType", "singleReminderTime", "reminderHour"],
      {
        reminderType: { hidden: true },
        singleReminderTime: { hidden: true },
        reminderHour: { hidden: true }
      }
    );
  } else {
    const formData = formRef.value.getFormData();
    formRef.value.setFormProps(
      ["reminderType", "singleReminderTime", "reminderHour"],
      {
        reminderType: { hidden: false },
        singleReminderTime: { hidden: formData.reminderType != 1 },
        reminderHour: { hidden: formData.reminderType == 1 }
      }
    );
  }
};

const taskChange = ({ key, value }) => {
  return new Promise(resolve => {
    const formData = formRef.value.getFormData();
    if (key === "loopType") {
      formRef.value.setFormProps("reminderSlot", {
        hidden: value == 1 || formData.reminderType == 1
      });
      if (value == 2) {
        remindSlotLabel.value = t("task_detail.form.week");
        formRef.value.setFormProps("reminderSlot", {
          label: t("task_detail.form.week")
        });
      } else if (value == 3) {
        remindSlotLabel.value = t("task_detail.form.month");
        formRef.value.setFormProps("reminderSlot", {
          label: t("task_detail.form.month")
        });
      }
    } else if (key === "reminderType") {
      formRef.value.setFormProps(
        ["singleReminderTime", "reminderSlot", "reminderHour", "loopType"],
        {
          reminderHour: { hidden: value == 1 },
          loopType: { hidden: value == 1 },
          singleReminderTime: { hidden: value != 1 },
          reminderSlot: { hidden: value == 1 || formData.loopType == 1 }
        }
      );
    } else if (key === "typeId") {
      typeChangeHandle(value);
      formRef.value.setFormData({
        typeId: value
      });
    }
    resolve(true);
  });
};

function getTaskHandle(row: TaskListProp) {
  // 单次提醒
  taskChange({ key: "reminderType", value: row.reminderType });
  // 重复方式
  taskChange({ key: "loopType", value: row.loopType });
  // 分类
  taskChange({ key: "typeId", value: row.typeId });
  try {
    // 非单次提醒
    if (row.reminderType == 2) {
      if (row.loopType == 2) {
        const weeks = JSON.parse(row.reminderWeek) as Array<{ index: number }>;
        remindData.value.week = weeks.map(v => Number(v?.index));
      } else if (row.loopType == 3) {
        const months = JSON.parse(row.reminderMonth) as Array<{
          index: number;
        }>;
        remindData.value.month = months.map(v => Number(v?.index));
      }
    }
  } catch (e) {
    console.error(e);
  }
}

const changeRemind = val => {
  formRef.value.setFormData({ reminderSlot: val });
};

const validateRemind = () => {
  const data = formRef.value.getFormData() as TaskListProp;
  if (data.reminderType == 2) {
    if (data.loopType == 2 && !remindData.value.week.length) {
      return { valid: false, msg: t("task_detail.form.select_week") };
    } else if (data.loopType == 3 && !remindData.value.month.length) {
      return { valid: false, msg: t("task_detail.form.select_month") };
    } else {
      return { valid: true };
    }
  } else {
    return { valid: true };
  }
};

const handleFormSubmit = (formData: TaskAddModel) => {
  let service = taskAdd;
  if (formData?.reminderType == 2) {
    if (formData?.loopType == 2) {
      formData.reminderWeek = JSON.stringify(
        remindData.value.week.map(v => {
          return { index: v };
        })
      );
      formData.reminderMonth = "[]";
    } else if (formData?.loopType == 3) {
      formData.reminderMonth = JSON.stringify(
        remindData.value.month.map(v => {
          return { index: v };
        })
      );
      formData.reminderWeek = "[]";
    } else {
      formData.reminderWeek = "[]";
      formData.reminderMonth = "[]";
    }
  } else {
    formData.reminderWeek = "[]";
    formData.reminderMonth = "[]";
  }

  // 处理营业和打烊的默认时间
  if (curSubId == 1 || curSubId == 2) {
    formData.reminderHour = "00:00:00";
  }

  if (formData?.id) {
    service = taskUpd;
  } else {
    Object.assign(formData, {
      versionId: props.taskParam?.versionId,
      subId: props.taskParam?.subId
    });
  }
  service(formData).then(res => {
    ElMessage({
      message: formData.id
        ? t("task_detail.form.edit_success")
        : t("task_detail.form.add_success"),
      type: "success"
    });
    emit("confirm");
    close();
  });
};

const setTypeList = () => {
  formRef.value.setFormProps("typeId", {
    options: props.typeList
  });
};

watch(
  () => [props.modelValue, props.formData],
  ([val, row]) => {
    if (val) {
      const rowData = cloneDeep(row) as TaskListProp;
      title.value = rowData?.id
        ? t("task_detail.form.edit_task")
        : t("task_detail.form.add_task");
      if (rowData?.id) {
        nextTick(() => {
          getTaskHandle(rowData);
          setTypeList();
          formRef.value.setFormData(rowData);
        });
      } else {
        nextTick(() => {
          formRef.value.reset();
          setTypeList();
          formRef.value.setFormData({
            loopType: 2,
            reminderType: 2,
            typeId: Number(props.taskParam.typeId) || ""
          });
          taskChange({ key: "loopType", value: 2 });
          taskChange({ key: "reminderType", value: 2 });
          taskChange({
            key: "typeId",
            value: Number(props.taskParam.typeId) || ""
          });
        });
      }
    }
  }
);
</script>

<style scoped>
:deep(.au-form-row) {
  padding-bottom: 16px;
}
</style>
